package tgc.edu.xzy.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.xzy.entity.Accredit;
import tgc.edu.xzy.entity.Journal;
import tgc.edu.xzy.entity.Lessee;
import tgc.edu.xzy.entity.LesseeAdmin;
import tgc.edu.xzy.entity.SysUser;
import tgc.edu.xzy.security.UserUtils;
import tgc.edu.xzy.service.ImpowerService;
import tgc.edu.xzy.service.LogService;
import tgc.edu.xzy.service.ZhAdminService;
import tgc.edu.xzy.service.ZhService;

@Controller
@RequestMapping(value="/lessee")
public class LesseeController {
	@Autowired
	private ZhService lesseeDAO;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private LogService journalDAO;
	@Autowired
	private ZhAdminService lesseeAdminDAO;
	@Autowired
	private ImpowerService accreditDAO;
	
	@RequestMapping(value="/all")
	public String all() {
		return "system/lessee_all";
	}
	@RequestMapping(value="/add_zh")
	public String add_zh() {
		return "LesseeAdmin/zh_add";
	}
	
	@RequestMapping(value="/gly")
	@ResponseBody
	public Boolean gly(String username, String password) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		boolean f = false;
		if(username.equals(user.getUsername()) && encoder.matches(password,user.getPassword())) {
			f = true;
		}
		return f;
	}
	
	@RequestMapping(value="save")
	public String save(Lessee model) {
		SysUser user = userUtils.getUser();
		LesseeAdmin lesseeAdmin = lesseeAdminDAO.findById(user.getId());
		model.setLesseeAdmin(lesseeAdmin);
		lesseeDAO.save(model);
		
		Accredit accredit = new Accredit();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		accredit.setLessee(model);
		accredit.setMonth(12);
		accredit.setBeginDate(sdf.format(date));
		accredit.setCost(0);
		Date newDate = stepMonth(date, 12);
		accredit.setOverDate(newDate);
		accreditDAO.save(accredit);
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String data = df.format(new Date());
		Journal journal = new Journal();
		journal.setDate(data);
		journal.setUsername(user.getUsername());
		journal.setOperationName("注册租户");
		journalDAO.save(journal);
		return "redirect:add_zh";
	}
	public Date stepMonth(Date sourceDate, int month) {
		 Calendar c = Calendar.getInstance();
	        c.setTime(sourceDate);
	        c.add(Calendar.MONTH, month);
	        return c.getTime();
	}
}
